<?php
declare(strict_types=1);

namespace Service\OrderService;

use App\Model\BbcModel\OrderExtends;
use Service\BaseService;
use Service\Code\CodeBuilder;
use Service\Code\Normal;
use Service\OrderService\Volidate\CashReturnOrderVolidate;
use App\Model\BbcModel\OrderReturn;
use App\Model\BbcModel\Order;
use App\Model\BbcModel\OrderGoods;
use App\Model\BbcModel\OrderReturnExtends;
use App\Model\BbcModel\Member;
use Service\PointsService\PointsService;
use Service\StorageService\StockService;
use App\Model\BbcModel\MnStoreGoods;
use App\Model\BbcModel\GoodsSale;
use App\Model\BbcModel\MnCommission;
use App\Model\BbcModel\MnBudget;
use Service\PayService\CashPayService;
use App\Model\BbcModel\Mnuser;
use App\Model\BbcModel\Goods;
use Service\PushService\PushYunCangApiService;
use Service\MessageService\SmsService;
use Service\OrderService\OrderLogService;
use Service\ChannelService\StoreConfigService;
use Service\HanshowService\HanshowService;
use Service\GoodsPointsService\GoodsPointsService;


class CashReturnOrderService extends BaseService
{
    public function returnOrder(int $cid,int $mn_sid,int $manager_id,int $cash_register_id,array $body) {        
        $mid=isset($body['mid'])?$body['mid']:0;
        $time=$body['time']??time();
        $sale_sn=isset($body['sn'])?$body['sn']:CodeBuilder::getCode($mn_sid);
        $result_returnorder_check = CashReturnOrderVolidate::instance()->checkReturnOrderData($cid,$mn_sid,$mid,$body);
        if( $result_returnorder_check['code'] != Normal::SUC ) {
            return $result_returnorder_check;
        }
        $body       = $result_returnorder_check['data'];
        $mid=isset($body['mid'])?$body['mid']:0;
        $memberinfo= Member::instance()->info(['mid'=>$body['mid']]);
        $orderreturndata=[
            'sale_type'=>2,
            'sn'=>$body['sn'],
            'reason'=>'其他原因',
            'reason_info'=>$body['reason_info']??'门店收银退货',
            'sale_sn'=>$sale_sn,
            'cd'=>$time,
            'status'=>1,
            'amount'=>$body['price_order'],
            'check_status'=>1,
            'mid'=>$mid,
            'mn_sid'=>$mn_sid,
            'cid'=>$cid,
            'pay_type'=>$body['pay_type'],
            'stoid'=>$body['stoid'],
            'mnid'=>4,
            'return_money'=>1,
            'type'=>$body['type']
        ];
        $extendsdata=[
            'order_id'=>$body['id'],
            'cd'=>$time,
            'cid'=>$cid,
            'mn_sid'=>$mn_sid,
            'giveup_money'=>0,
            'pay_way'=> implode(',', $body['pay_way']),
            'cash'=> isset($body['cash'])?$body['cash']:0,
            'scan_pay'=> isset($body['scan_pay'])?$body['scan_pay']:0,
            'scan_rece'=> isset($body['scan_rece'])?$body['scan_rece']:0,
            'pos'=> isset($body['pos'])?$body['pos']:0,
            'storecard'=> isset($body['storecard'])?$body['storecard']:0,
            'storecard_id'=> isset($body['storecard_id'])?$body['storecard_id']:0,
            'balance'=> isset($body['balance'])?$body['balance']:0,
            'coupon'=> isset($body['coupon'])?$body['coupon']:0,
            'points'=> isset($body['points'])?$body['points']:0,
            'goods_points'=>isset($body['goods_points'])?$body['goods_points']:0,
            'cashregister_id'=>$cash_register_id,
            'casher'=>$manager_id,
            'give_points'=>$body['orderextends']['give_points']??0
        ];
        try{
            Order::instance()->startTrans();
            $orderres= Order::instance()->edit(['id'=>$body['id']], ['status'=>0,'md'=>$time]);
            if(!$orderres){
                Order::instance()->rollback();
                return Normal::returnCode(Normal::FAIL, '原始订单修改失败'); 
            }
            $order_goodsres= OrderGoods::instance()->edit(['order_id'=>$body['id']], ['order_status'=>1]);
            if(!$order_goodsres){
                Order::instance()->rollback();
                return Normal::returnCode(Normal::FAIL, '原始订单商品失败'); 
            }
            $orderreturnres= OrderReturn::instance()->add($orderreturndata);
            if(!$orderreturnres){
                Order::instance()->rollback();
                return Normal::returnCode(Normal::FAIL, '退货单新增失败'); 
            }
            $extendsdata['order_return_id']=$orderreturnres;
            $orderreturnextendsres= OrderReturnExtends::instance()->add($extendsdata);
            if(!$orderreturnextendsres){
                Order::instance()->rollback();
                return Normal::returnCode(Normal::FAIL, '退货单扩展新增失败'); 
            }
            if($mid>0){
                $memberconsumeres= Member::instance()->where(['mid'=>$mid])->decrement('consume',$body['price_order']);
                if(!$memberconsumeres){
                    Order::instance()->rollback();
                    return Normal::returnCode(Normal::FAIL, '更新累计消费失败');
                }
            }
            
            
            /**
             * 储值积分操作
             */
            if($extendsdata['points']>0){
                $result_user_points = PointsService::instance()->returnPointsByReturnOrder($cid, $mid, $mn_sid, $extendsdata['points'],[
                    'give_points'          => $extendsdata['give_points']
                ]);
                if( $result_user_points['code'] != Normal::SUC ) {
                    OrderReturn::instance()->rollback();
                    return $result_user_points;
                }
            }
            
            /**
             * 储值卡消费
             */
            if($extendsdata['storecard_id']){
                $result_user_storecard = StoreCardService::instance()->userStoreCardReBack($extendsdata['storecard_id'],$extendsdata['storecard'],[
                    'sale_sn'  => $sale_sn,
                    'cid'       => $cid,
                    'mn_sid'    => $mn_sid
                ]);
                if( $result_user_storecard['code'] != Normal::SUC ) {
                    OrderReturn::instance()->rollback();
                    return $result_user_storecard;
                }
            }
            //积分抵现
            if($extendsdata['goods_points']>0&&$body['use_points']>0){
                $goodsPointsRes= GoodsPointsService::instance()->addGoodsPoints($cid, $body['mid'], $mn_sid, $body['use_points'], $body['sn'], "售后积分(订单号:{$body['sn']})");
                if($goodsPointsRes['code']==Normal::FAIL){
                    OrderReturn::instance()->rollback();
                    return $goodsPointsRes;
                }
            }
            //赠送积分返还
            if($body['return_goods_points']>0&&$body['status']>=50 && $body['mid']>0){
                $returnGoodsPointsRes= GoodsPointsService::instance()->deductGoodsPoints($cid, $body['mid'], $mn_sid, $body['return_goods_points'], $body['sn'], "售后返赠送积分(订单号:{$body['sn']})");
                if($returnGoodsPointsRes['code']==Normal::FAIL){
                    OrderReturn::instance()->rollback();
                    return $returnGoodsPointsRes;
                }
            }
            
            if($body['return_parent_points']>0&&$body['status']>=50&& $body['mid']>0&&$memberinfo['parent_id']>0){
                $returnparentGoodsPointsRes= GoodsPointsService::instance()->deductGoodsPoints($cid, $memberinfo['parent_id'], $mn_sid, $body['return_parent_points'], $body['sn'], "下级售后返赠送积分(订单号:{$body['sn']})");
                if($returnparentGoodsPointsRes['code']==Normal::FAIL){
                    OrderReturn::instance()->rollback();
                    return $returnparentGoodsPointsRes;
                }
            }
            
            /**
             * 商品处理
             */
            $dealReturnOrderGoods=$this->dealReturnOrderGoods($cid, $mn_sid, $body['goods'], ['sale_sn'=>$sale_sn,'order_return_id'=>$orderreturnres,'time'=>$time]);
            if( $dealReturnOrderGoods['code'] != Normal::SUC ) {
                OrderReturn::instance()->rollback();
                return $dealReturnOrderGoods;
            }
            
            /**
             * 处理分佣
             */
            $dealReturnOrderCommission= $this->dealReturnOrderCommission($body);
            if( $dealReturnOrderCommission['code'] != Normal::SUC ) {
                OrderReturn::instance()->rollback();
                return $dealReturnOrderCommission;
            }
            
            /**
             * 在线支付原路退货
             */
            if($extendsdata['scan_rece'] > 0){
                $order_ids = Order::instance()
                    ->where('pay_sn',$body['pay_sn'])
                    ->pluck('id')->toArray();
                $total_fee = OrderExtends::instance()
                    ->whereIn('order_id',$order_ids)
                    ->sum('scan_rece');
                $mnuser= Mnuser::instance()->info(['id'=>$mn_sid]);
                $extendsPaydata=[
                    'scan_rece_type'=>$body['orderextends']['scan_rece_type'],
                    'out_refund_no'=>$sale_sn,
                    'out_trade_no'=>$body['pay_sn'],
                    'body'=>'门店收银退款',
                    'total_fee'=>$total_fee,
                    'refund_fee'=>$extendsdata['scan_rece'],
                    'scan_sn'=>$body['orderextends']['scan_sn'],
                    'store_type'=>$mnuser['type'],
                    'order_id'=>$orderreturnres
                ];
                $payReturn= CashPayService::instance()->userPayReturn($cid, $mn_sid, 4, $extendsPaydata);
                if($payReturn['code']!= Normal::SUC){
                   OrderReturn::instance()->rollback();
                   return  $payReturn;
                }
            }
            OrderReturn::instance()->commit();
            if($body['type']==4&&$body['push_success']==1&&$body['pay_success']==1){
                $syncAfterSaleData['after_sale_status'] = 1;
                $syncAfterSaleData['order_sn'] = $body['sn'];
                $syncAfterSaleData['cid'] = $body['cid'];
                $syncAfterSaleData['exceptReason'] = '门店收银机直接退货退款-售后';
                $push_order_aftersale_result =PushYunCangApiService::instance()->push($cid,'OrderAfterSale',$syncAfterSaleData);
                if( $push_order_aftersale_result['code'] == Normal::SUC ){
                    OrderReturn::instance()->edit(['id'=>$orderreturnres], ['notice_cloud'=>1]);
                }
            }
            if($body['type']==4&&$body['push_success']==1&&$body['pay_success']==0){
                $syncCancelData = [
                    'orderSn' => $body['sn'],
                    'exceptReason' => '门店收银机直接退货退款-售后取消',
                    'cid' => $body['cid']
                ];
                $push_order_cancel_result =PushYunCangApiService::instance()->push($cid,'OrderCancel',$syncCancelData);
                if( $push_order_cancel_result['code'] == Normal::SUC ){
                    OrderReturn::instance()->edit(['id'=>$orderreturnres], ['notice_cloud'=>1]);
                    
                }
            }
            $hanshow_config=StoreConfigService::instance()->getConfig('hanshow_config', $mn_sid);
            $hanshow_show=$hanshow_config['show']??0;
            if($hanshow_show==1){
                $hanshow_data=[
                     'config'=>$hanshow_config,
                     'goodsIds'=> array_column($body['goods'],'goods_id'),
                     'mn_sid'=>$mn_sid
                 ];
                 HanshowService::instance()->publishMsg($hanshow_data);
            }
            $logdata=['order_id' => $body['id'], 'order_status' => 0, 'msg' => '售后成功，取消订单'];
            OrderLogService::instance()->addLog($logdata);
            return Normal::returnCode(Normal::SUC, '操作成功',['sn'=>$sale_sn,'order_id'=>$orderreturnres]);
        } catch (\Exception $ex) {
            OrderReturn::instance()->rollback();
            return Normal::returnCode(Normal::FAIL, '失败'.$ex->getMessage());
        }
    }
    
    /**
     * 处理退货订单商品
     * @param int $cid
     * @param int $mn_sid
     * @param array $order_goods
     * @param array $extra
     * @return type
     */
    public function dealReturnOrderGoods(int $cid,int $mn_sid,array $order_goods, array $extra = []) {
        foreach ($order_goods as $key => $value) {
            $batchs= json_decode($value['batch_actual'], true);
            $stockExtra=[
                'goods_id'=>$value['goods_id'],
                'bill_type'=>3,
                'bill_id'=>$extra['order_return_id'],
                'bill_code'=>$extra['sale_sn'],
                'num'=>$value['num'],
                'batch_no'=>$batchs[0]['batch_no'],
                'expire'=>0,
                'time'=>$extra['time']
            ];
            $stockresult= StockService::instance()->addStock($cid, $mn_sid, $stockExtra);
            if($stockresult['code']!= Normal::SUC){
                return $stockresult;
            }
            MnStoreGoods::instance()->where(['mn_sid'=>$mn_sid,'goods_id'=>$value['goods_id']])->decrement('num_sale',$value['num']);
            $goodssalsres= Goods::instance()->where(['id'=>$value['goods_id']])->decrement('num_sale',$value['num']);
            if(!$goodssalsres){
                //return Normal::returnCode(Normal::FAIL, $goodsname.'销量失败');
            }
            $goodssalsres2= Goods::instance()->where(['id'=>$value['goods_id']])->decrement('fictitious_sale',$value['num']);
            if(!$goodssalsres2){
                //return Normal::returnCode(Normal::FAIL, $goodsname.'销量失败2');
            }
            $goodssale= GoodsSale::instance()->info(['goods_id'=>$value['goods_id']]);
            if($goodssale){
                $goodssalsres4=GoodsSale::instance()->where(['id'=>$goodssale['id']])->decrement('num_sale',$value['num']);
                if(!$goodssalsres4){
                    //return Normal::returnCode(Normal::FAIL, $goodsname.'销量失败4');
                }
            }
            
        }
        return Normal::returnCode(Normal::SUC,'操作成功');
    }
    
    /**
     * 处理退款订单分佣
     * @param array $param
     * @return type
     */
    public function dealReturnOrderCommission(array $param) {
        $commission=MnCommission::instance()->lists(['sn'=>$param['sn'],'mn_sid'=>$param['mn_sid'],'df'=>0]);
        if(!empty($commission)){
            $qStore=Mnuser::instance()->info(['id'=>$param['mn_sid']]);
            if($commission[0]['status']==1){
                //佣金已转入可提现金额
                $qEditData=[
                    'wallet_income'=>$qStore['wallet_income']-$param['distribute_money'],
                    'wallet_accumulate_income'=>$qStore['wallet_accumulate_income']-$param['distribute_money'],
                    'all_sell'=>$qStore['all_sell']-$param['price_order']
                ];
                $budget['mid']=$qStore['mid'];
                $budget['mn_sid']=$qStore['id'];
                $budget['mnid']=$qStore['mnid'];
                $budget['type']=0;
                $budget['sn']=$param['sn'];
                $budget['money']=$param['distribute_money'];
                $budget['amount']=$qEditData['wallet_income'];
                $budget['remark']='订单:'.$param['sn'].'售后退款';
                $budget['cd']= time();
                $mnbudgetres=MnBudget::instance()->add($budget);
                if(!$mnbudgetres){
                    return Normal::returnCode(Normal::FAIL, '退款记录写入失败');
                }
            }else{
                //佣金还未转入可提现金额
                $qEditData=[
                    'frozen_income'=>$qStore['frozen_income']-$param['distribute_money'],
                    'all_sell'=>$qStore['all_sell']-$param['price_order']
                ];

            }
            $mncommissionres=MnCommission::instance()->edit(['sn'=>$param['sn'],'mn_sid'=>$param['mn_sid']],['df'=>1]);
            if(!$mncommissionres){
                return Normal::returnCode(Normal::FAIL, '分佣记录更新失败');
            }
            $mnuserres=Mnuser::instance()->edit(['id'=>$param['mn_sid']],$qEditData);
            if(!$mnuserres){
                return Normal::returnCode(Normal::FAIL, '用户资金更新失败');
            }
        }
        return Normal::returnCode(Normal::SUC,'操作成功');
    }
}
